﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;

namespace TemplateEngine
{
    /// <summary>
    /// Contructs templates from Embedded Resources
    /// </summary>
    public class ResourceTemplateFactory : ITemplateFactory
    {
        private Assembly _source;
        private String _root = "";

        /// <summary>
        /// Constructs a ResourceTemplateFactory that will look in the calling assembly
        /// </summary>
        public ResourceTemplateFactory() : this("")        {}
        /// <summary>
        /// Constructs a ResourceTemplateFactory that will look in the calling assembly and will use the specified prefix when looking for templates
        /// </summary>
        /// <param name="root">A prefix to future lookups.  A . will be automatically appended to the root if missing</param>
        public ResourceTemplateFactory(String root):this(root, Assembly.GetCallingAssembly()){}
        /// <summary>
        /// Constructs a ResourceTemplateFactory that will look in the specified assembly
        /// </summary>
        /// <param name="assemblyContainingResources">The assembly that contains the resources to load</param>
        public ResourceTemplateFactory(Assembly assemblyContainingResources) : this("", assemblyContainingResources) 
        { Contract.Requires(assemblyContainingResources != null); }
        /// <summary>
        /// Constrcuts a ResourceTemplateFactory that will look in the specfied assembly and will use the specified prefix when looking for templates
        /// </summary>
        /// <param name="root">A prefix to future lookups.  A . will be automatically appended to the root if missing</param>
        /// <param name="assemblyContainingResources">The assembly that contains the resources to load</param>
        public ResourceTemplateFactory(String root, Assembly assemblyContainingResources)
        {
            Contract.Requires(assemblyContainingResources != null);
            Contract.Ensures(_root != null);
            Contract.Ensures(_source != null);
            _source = assemblyContainingResources;
            _root = (root ?? "").Trim();
            if (_root.Length != 0 && !_root.EndsWith(".", StringComparison.OrdinalIgnoreCase))
            {
                _root += ".";
            }
        }

        private Dictionary<String, ITemplate> _cachedTemplates = new Dictionary<string, ITemplate>();
        /// <summary>
        /// Fecthes or Creates a template with the specified name
        /// </summary>
        /// <param name="name">The name of the template to find or create</param>
        /// <returns>The corresponding template or null if none found that match</returns>
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")]
        public ITemplate GetTemplate(String name)
        {
            String fullname = _root + name;
            ITemplate result;
            lock (_cachedTemplates)
            {
                if (!_cachedTemplates.TryGetValue(fullname, out result))
                {
                    result = LoadTemplate(fullname);
                    _cachedTemplates.Add(fullname, result);
                }
            }
            return result;
        }

        /// <summary>
        /// Creates a template from the specified calling assembly resource.  Result will not be cached.
        /// </summary>
        /// <param name="name">The name of the template to create</param>
        /// <returns>The corresponding template or null if none found that match</returns>
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")]
        public static ITemplate GetTemplateNoCache(String name)
        {
            Contract.Requires(name != null);
            Contract.Requires(name.Length > 0);
            String text = Common.ResourceUtil.GetResourceAsText(Assembly.GetCallingAssembly(), name);
            return text != null ? TemplateConverter.loadTemplate(text) : null;
        }

        /// <summary>
        /// Creates a template from the specified assembly resource.  Result will not be cached.
        /// </summary>
        /// <param name="name">The name of the template to create</param>
        /// <param name="source">The assembly that has the resource to load</param>
        /// <returns>The corresponding template or null if none found that match</returns>        
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1")]
        public static ITemplate GetTemplateNoCache(Assembly source, String name)
        {
            Contract.Requires(source != null);
            Contract.Requires(name != null);
            Contract.Requires(name.Length > 0);
            String text = Common.ResourceUtil.GetResourceAsText(source, name);
            return text != null ? TemplateConverter.loadTemplate(text) : null;
        }

        private ITemplate LoadTemplate(String name)
        {
            Contract.Requires(name != null);
            Contract.Requires(name.Length > 0);
            String text = Common.ResourceUtil.GetResourceAsText(_source, name);
            return text != null ? TemplateConverter.loadTemplate(text) : null;
        }

        [ContractInvariantMethod]
        private void AlwaysTrue()
        {
            Contract.Invariant(_root != null);
            Contract.Invariant(_source != null);
            Contract.Invariant(_cachedTemplates != null);
        }
    }
}
